package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.Spu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {

@Autowired
private SpuMapper spuMapper;
@Autowired
private CategoryService categoryService;
@Autowired
private BrandService brandService;


    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        //分页
        PageHelper.startPage(page,rows);

        //过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
       //搜索条件过滤
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%");
        }
        //上下架过滤
         if (saleable!=null){
            criteria.andEqualTo("saleable",saleable);
         }
         //时间排序
           example.setOrderByClause("update_time DESC");

         //查询结果
        List<Spu> spuList = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //封装分页结果
        PageInfo<Spu> Info = new PageInfo<>(spuList);
        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(spuList, SpuDTO.class);

        //查询商品分类，品牌
        spuDTOS.forEach( spuDTO -> {
            //查询分类，查询得到的DTO集合，并把集合循环遍历，取出每个name,并且拼接成一个字符串
              String categoryName=categoryService.queryCategoryByIds(spuDTO.getCategoryIds())
            .stream()
            .map(CategoryDTO::getName).collect(Collectors.joining("/"));
              spuDTO.setCategoryName(categoryName);
              //根据品牌id,查询品牌信息
              spuDTO.setBrandName(this.brandService.queryBrandById(spuDTO.getBrandId()).getName());
                });

        return new PageResult<>(Info.getTotal(),Info.getPages(),spuDTOS);
    }
}
